package com.cyj.controller;

import com.cyj.entity.Admin;
import com.cyj.entity.Anime;
import com.cyj.entity.FileEntity;
import com.cyj.entity.User;
import com.cyj.service.AdminService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/adminMainView")
    public String adminMainView(){
        return "adminMain";
    }

    @RequestMapping("/adminDetails")
    public String adminDetails(){
        return "adminDetails";
    }

    @RequestMapping(value="/adminLogin",produces = "text/html;charset=utf-8")
    public String adminLogin(Admin admin, Model model, HttpSession session){
        System.out.println(admin);
        Map<String,Object> map =  new HashMap<String,Object>();
        map.put("adminName",admin.getAdminName());
        map.put("adminPassword",admin.getAdminPassword());
        map.put("lastLoginTime",new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

        Admin loginAdmin = adminService.selectAdmin(map);

        if (loginAdmin!=null){
            adminService.updateAdminLoginTime(map);
            session.setAttribute("admin",adminService.selectAdmin(map));

            return "adminMain";
        }else {

            model.addAttribute("error","账号或密码错误");
            return "forward:../adminLogin.jsp";
        }
    }

    @ResponseBody
    @RequestMapping(value = "/adminBy",produces = "application/json;charset=utf-8")
    public Map adminBy(HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();
        Integer adminId = Integer.parseInt(request.getParameter("adminId"));

        map.put("adminId",adminId);

        Admin admin = adminService.selectAdmin(map);

        if(admin!=null){
            map.put("code", 200);
            map.put("msg", "管理员查找成功");
            map.put("data",admin);
        }else {
            map.put("code", 100);
            map.put("msg", "管理员查找失败");
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/updateAdmin",produces = "application/json;charset=utf-8")
    public Map updateAdmin(HttpServletRequest request,HttpSession session){

        Map<String, String[]> map = request.getParameterMap();
        Integer adminId = Integer.parseInt(request.getParameter("adminId"));
        Admin admin = new Admin();

        try {
            BeanUtils.populate(admin,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        admin.setAdminId(adminId);
        System.out.println("前台修改传参："+admin);

        int num = adminService.updateAdmin(admin);

        Map<String,Object> map2 = new HashMap<String,Object>();

        if (num>0){
            session.removeAttribute("admin");
            map2.put("adminId",adminId);
            session.setAttribute("admin",adminService.selectAdmin(map2));

            map2.put("code", 200);
            map2.put("msg", "管路员修改成功");
        }else {
            map2.put("code", 100);
            map2.put("msg", "管路员修改失败");
        }

        return map2;
    }

    @ResponseBody
    @RequestMapping(value = "/uploadPicture",produces = "application/json;charset=utf-8")
    public Map uploadPicture(HttpServletRequest request, FileEntity entity,HttpSession session){

        //设置要存放图片的目录 (例如：c:/tomcat/webapp/upload)
        String realpath = request.getServletContext().getRealPath("/")+"upload/";

        String fileName = entity.getUploadFile().getOriginalFilename();
        System.out.println(fileName);

        //把路径封装为file对象（因为file可以判断文件或者目录是否存在，如果不存在就可以创建）
        File targetPath = new File(realpath+fileName);

        //判断文件或者路径是否存在
        if (!targetPath.exists()){
            targetPath.mkdirs();
        }
        try {
            //使用MultipartFile的transferTo方法保存从前端传过来MultipartFile对象
            entity.getUploadFile().transferTo(targetPath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //获取要存到数据库里面的路径
        String picture = "http://192.168.44.48:8080"+request.getContextPath()+"/upload/"+fileName;
        System.out.println(picture);

        Integer adminId = Integer.parseInt(request.getParameter("adminId"));

        Admin admin = new Admin();
        admin.setAdminId(adminId);
        admin.setPicture(picture);

        System.out.println(admin);

        int num = adminService.updateAdmin(admin);

        Map<String,Object> map = new HashMap<String,Object>();

        if (num>0){
            session.removeAttribute("admin");
            map.put("adminId",adminId);
            session.setAttribute("admin",adminService.selectAdmin(map));

            map.put("code", 200);
            map.put("msg", "管理员头像上传成功");
        }else {
            map.put("code", 100);
            map.put("msg", "管理员头像上传失败");
        }

        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/logout",produces = "application/json;charset=utf-8")
    public Map logout(HttpSession session){
        session.removeAttribute("admin");

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("code", 200);
        map.put("msg", "退出登录成功");

        return map;
    }
}
